/**
 * 漆水河 脚手架基础公开课
 * 2022/8/13 --- 2022/12/13
 * 有疑问可加QQ群: 809126489，后续会持续输出与大家一起成长
 */
package com.qishuihe.common.infrastructure.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.qishuihe.baseinterface.basevo.vo.BaseVO;
import com.qishuihe.baseinterface.utils.WebResponseUtils;
import com.qishuihe.common.infrastructure.exception.RestPWException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        BaseVO baseVO = new BaseVO();
        baseVO.setCode(HttpStatus.UNAUTHORIZED.value());
        baseVO.setMessage("认证失败或链接失效，请重新登录或获取链接");
        if(e instanceof RestPWException ){
            baseVO.setMessage(e.getMessage());
        }

        WebResponseUtils.renderResponse(httpServletResponse, JSONObject.toJSONString(baseVO));
    }
}
